﻿using System;
using System.ServiceModel;
using System.Data;
using System.Windows.Forms;
using System.Security.Principal;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
using System.Security;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using Mota.EditModule;
using System.Linq;
using System.Configuration;
using InformationModule;
using System.Threading;
using System.Globalization;
using EagleEyeCoreLibrary;

namespace Mota.TestApplication
{
    public partial class TestForm : Form
    {
        private Dictionary<string, object> overrideValuesList = new Dictionary<string, object>();
        private string id = String.Empty;
        private Regex cipherRegex = new Regex(@"\{(\w+.\w+)\}", RegexOptions.IgnoreCase);
        private Regex idRegex = new Regex(@"\[(.+)\]", RegexOptions.IgnoreCase);
        private ConnectionConfigs connectionConfig;
        private string LastId { get { return id;} }
        private string Id
        {
            get
            {
                if (!String.IsNullOrEmpty(this.id))
                    return this.id;

                if (clbRequirements.SelectedItem != null)
                {
                    Match m = idRegex.Match(clbRequirements.SelectedItem.ToString());
                    if (m.Groups[1].Success)
                        return m.Groups[1].Value;
                }
                
                return String.Empty;
            }
        }

        private string CurrentNameOrig
        {
            get
            {
                if (clbRequirements.SelectedItem != null)
                {
                    Match m = cipherRegex.Match(clbRequirements.SelectedItem.ToString());
                    if (m.Groups[1].Success)
                    {
                        return m.Groups[1].Value;
                    }
                }
                return String.Empty;
            }
        }   

        public TestForm()
        {
            InitializeComponent();
            Thread.CurrentThread.CurrentCulture = new CultureInfo("uk-UA");
            Thread.CurrentThread.CurrentUICulture = new CultureInfo("uk-UA");
            connectionConfig = new ConnectionConfigs() { 
                    ConnectionString = ConfigurationManager.ConnectionStrings["gryphonedevelop"].ConnectionString
                };
            lbOverrideValues.Format+=lbOverrideValues_Format;
            EditForm.SetInfoModuleInitiator(new InfoInvoke());
        }

        void lbOverrideValues_Format(object sender, ListControlConvertEventArgs e)
        {
            dynamic item = (dynamic)e.ListItem;
            string key = item.Key,
                   value = item.Value;
            e.Value = key + ": " + value; 
        }

        private void button5_Click(object sender, EventArgs e)
        {
            WindowsIdentity wi = WindowsIdentity.GetCurrent();
            //queryBox.Text = wi.User + ";" + wi.Name + ";" + wi.Token + ";" + wi.AuthenticationType;
        }

        private void Form1_Layout(object sender, LayoutEventArgs e)
        {
#if DEVELOP
            SplashScreen.CloseForm();
#endif
        }


        private void button12_Click(object sender, EventArgs e)
        {
            //InfoModule IM = new InfoModule("Applications", null);
        }
        
        private void TestForm_Load(object sender, EventArgs e)
        {
            LoadRequirements();
        }

        private void LoadRequirements()
        {
            clbRequirements.Items.Clear();
            string path = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath),
                            "Requirements.txt");
            if (File.Exists(path))
            {
                // Open the file to read from. 
                using (StreamReader sr = File.OpenText(path))
                {
                    string s = "";
                    while ((s = sr.ReadLine()) != null)
                    {
                        clbRequirements.Items.Add(s);
                    }
                }
            }
        }

        private void btnRequirements_Click(object sender, EventArgs e)
        {
            LoadRequirements();
        }

        private void ExecTest(EditFormMode mode,String inputId = "",Dictionary<string,object> values = null)
        {
            try
            {

                if (CurrentNameOrig != String.Empty)
                {
                    String id = inputId;
                    connectionConfig.ViewName = CurrentNameOrig;
                    switch (EditForm.ShowDialog(connectionConfig, mode, ref id,values))
                    {
                        case (DialogResult.OK):
                            MessageBox.Show("Result OK");
                            break;
                        case (DialogResult.Cancel):
                            MessageBox.Show("Canceled");
                            break;
                    }
                    this.id = id.ToString();
                }


            }
            catch (System.Exception ex)
            {
#if MAT
                EventAppLogger.WriteAppError(ex, connectionConfig.ConnectionString);
#endif
                MessageBox.Show(ex.Message, ex.GetType().ToString(), MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void btnInsert_Click(object sender, EventArgs e)
        {
            ExecTest(EditFormMode.Insert);
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            ExecTest(EditFormMode.Update, Id);
        }

        private void btnCopy_Click(object sender, EventArgs e)
        {
            ExecTest(EditFormMode.Copy, Id);
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            ExecTest(EditFormMode.Delete, Id);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            overrideValuesList.Add(tbName.Text, tbValue.Text);
            tbName.Text = String.Empty;
            tbValue.Text = String.Empty;
            lbOverrideValues.DataSource = overrideValuesList.ToList();
        }

        private void btnInsertWithOverrideDefault_Click(object sender, EventArgs e)
        {
            ExecTest(EditFormMode.Insert, String.Empty,overrideValuesList);
        }
    }
}
